package org.jitsi.meet.sdk;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableNativeMap;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * 代替正式接口返回头像图片的测试Module
 * Created by ly on 2018/3/9.
 */

public class IconModule extends ReactContextBaseJavaModule {
    private final String ICON = "test.png";

    public IconModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "IconModule";
    }

    /**
     * 获取图片并进行编码到react端
     */
    @ReactMethod
    public void getIcon(Callback callback) {
        WritableNativeMap data = new WritableNativeMap();
        String result = null;

        try {
            InputStream in = getReactApplicationContext().getAssets().open(ICON);
            result = Image2Base64(in);

            in.close();
        } catch (IOException e) {
            e.printStackTrace();

            result = "error";
        }

        data.putString("data", result);
        callback.invoke(data);
    }

    /**
     * 将图片转换为base64数组
     * @param in 图片输入流
     * @return 结果的Base64字符串
     */
    private String Image2Base64(InputStream in) {
        //先将输入流转换为bitmap再转换为byte数组来进行Base64编码
        //不直接使用in.available()是因为真正接口此处为加载网络图片，无法获取字节长度
        Bitmap temp = BitmapFactory.decodeStream(in);
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        temp.compress(Bitmap.CompressFormat.PNG, 100, out);
        byte[] data = Base64.encode(out.toByteArray(), Base64.DEFAULT);
        String result = new String(data, Charset.forName("UTF-8"));

        temp.recycle();
        return result;
    }
}
